package com.luobr.backend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luobr.backend.api.aliyunai.AliYunAiApi;
import com.luobr.backend.api.aliyunai.model.CreateImageSynthesisTaskRequest;
import com.luobr.backend.api.aliyunai.model.CreateImageSynthesisTaskResponse;
import com.luobr.backend.common.ResponseCode;
import com.luobr.backend.constant.ImageConstant;
import com.luobr.backend.constant.UserConstant;
import com.luobr.backend.exception.BusinessException;
import com.luobr.backend.exception.ThrowUtils;
import com.luobr.backend.manage.cache.CacheManager;
import com.luobr.backend.manage.upload.UploadAndParseImage;
import com.luobr.backend.manage.upload.UploadAndParseImageByUrl;
import com.luobr.backend.manage.upload.UploadAndParseImageTemplate;
import com.luobr.backend.model.dto.image.*;
import com.luobr.backend.model.entity.Image;
import com.luobr.backend.model.entity.Space;
import com.luobr.backend.model.entity.User;
import com.luobr.backend.model.enums.ReviewStatusEnum;
import com.luobr.backend.model.vo.image.ImageVO;
import com.luobr.backend.model.vo.user.UserLoginVO;
import com.luobr.backend.service.ImageService;
import com.luobr.backend.mapper.ImageMapper;
import com.luobr.backend.service.SpaceService;
import com.luobr.backend.service.UserService;
import com.luobr.backend.utils.ColorSimilarUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 罗念笙
 * @description 针对表【image(图片)】的数据库操作Service实现
 * @createDate 2025-02-25 16:01:18
 */
@Slf4j
@Service
public class ImageServiceImpl extends ServiceImpl<ImageMapper, Image> implements ImageService {

    @Resource
    private UploadAndParseImage uploadAndParseImage;
    @Resource
    private UploadAndParseImageByUrl uploadAndParseImageByUrl;
    @Resource
    private UserService userService;
    @Resource
    private CacheManager cacheManager;
    @Resource
    private SpaceService spaceService;
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    private AliYunAiApi aliYunAiApi;

    @Override
    public ImageVO uploadImage(Object inputSource, ImageUploadRequest imageUploadRequest, UserLoginVO loginUser) {
        // 未登录的用户不允许上传图片
        ThrowUtils.throwIf(loginUser == null, ResponseCode.NOT_LOGIN_ERROR);
        // 校验空间权限
        Long spaceId = imageUploadRequest.getSpaceId();
        if (spaceId != null) {
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ResponseCode.NOT_FOUND_ERROR, "空间不存在");
            // 必须空间创建人（管理员）才能上传
//            if (!loginUser.getId().equals(space.getUserId())) {
//                throw new BusinessException(ResponseCode.NO_AUTH_ERROR, "没有空间权限");
//            }
            // 校验额度
            if (space.getTotalCount() >= space.getMaxCount()) {
                throw new BusinessException(ResponseCode.OPERATION_ERROR, "空间条数不足");
            }
            if (space.getTotalSize() >= space.getMaxSize()) {
                throw new BusinessException(ResponseCode.OPERATION_ERROR, "空间大小不足");
            }
        }
        // 校验图片权限
        Long imgId = imageUploadRequest.getId();
        if (imgId != null) {
            // 更新图片需要校验图片是否存在
            Image image = this.getById(imgId);
            ThrowUtils.throwIf(ObjUtil.isNull(image), ResponseCode.NOT_FOUND_ERROR, "图片不存在！");
            checkImageAndSpaceAuth(loginUser,image);
        }
        // 上传图片并获取图片信息
        // 根据inputSource类型区分上传方式
        UploadAndParseImageTemplate uploadAndParseImageTemplate = uploadAndParseImage;
        if (inputSource instanceof String) {
            uploadAndParseImageTemplate = uploadAndParseImageByUrl;
        }
        // 共有图片目录采用 photoGallery/public/userId 划分 ; 私有图片目录采用 photoGallery/space/spaceId 划分
        String uploadPathPrefix = ObjUtil.isNull(spaceId) ? ImageConstant.FILE_PATH_PREFIX.PUBLIC : ImageConstant.FILE_PATH_PREFIX.SPACE;
        ImageParseResult imageParseResult = uploadAndParseImageTemplate.uploadAndParseImage(inputSource,
                uploadPathPrefix + "/" + (ObjUtil.isNull(spaceId) ? loginUser.getId() : spaceId));
        // 解析图片信息
        Image image = ImageParseResult.parseVoToObj(imageParseResult);
        image.setUserId(loginUser.getId());
        image.setSpaceId(spaceId);
        String imgName = imageUploadRequest.getImgName();
        if (StrUtil.isNotBlank(imgName)) {
            image.setName(imgName);
        }
        // 修改图片审核信息
        this.filterReviewImage(image, loginUser);
        if (imgId != null) {
            image.setId(imageUploadRequest.getId());
            image.setEditTime(new Date());
        }
        // 开启事务，保存图片信息
        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            ThrowUtils.throwIf(!this.saveOrUpdate(image),ResponseCode.OPERATION_ERROR, "保存图片失败！");
            if (finalSpaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
                        .setSql("totalSize = totalSize + " + image.getImgSize())
                        .setSql("totalCount = totalCount + 1")
                        .update();
                ThrowUtils.throwIf(!update, ResponseCode.OPERATION_ERROR, "额度更新失败");
            }
            return true;
        });
        return ImageVO.objToVo(image, loginUser);
    }

    @Override
    public int uploadImageByBatch(ImageUploadByBatchRequest imageUploadByBatchRequest, UserLoginVO loginUser) {
        // 校验参数
        Integer count = imageUploadByBatchRequest.getCount();
        ThrowUtils.throwIf(count > 30, ResponseCode.PARAMS_ERROR, "最多 30 条");
        // 要抓取的地址
        String searchText = imageUploadByBatchRequest.getSearchText();
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        String namePrefix = imageUploadByBatchRequest.getNamePrefix();
        if (StrUtil.isBlank(namePrefix)) {
            namePrefix = searchText;
        }
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("获取页面失败", e);
            throw new BusinessException(ResponseCode.OPERATION_ERROR, "获取页面失败");
        }
        Element div = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isNull(div)) {
            throw new BusinessException(ResponseCode.OPERATION_ERROR, "获取元素失败");
        }
        Elements imgElementList = div.select("img.mimg");
        int uploadCount = 0;
        for (Element imgElement : imgElementList) {
            String fileUrl = imgElement.attr("src");
            if (StrUtil.isBlank(fileUrl)) {
                log.info("当前链接为空，已跳过: {}", fileUrl);
                continue;
            }
            // 处理图片上传地址，防止出现转义问题
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }
            // 上传图片
            ImageUploadRequest imageUploadRequest = new ImageUploadRequest();
            imageUploadRequest.setImgName(namePrefix + (uploadCount + 1));
            try {
                ImageVO imageVO = this.uploadImage(fileUrl, imageUploadRequest, loginUser);
                log.info("图片上传成功, id = {}", imageVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败", e);
                continue;
            }
            if (uploadCount >= count) {
                break;
            }
        }
        return uploadCount;
    }

    @Override
    public void deleteImage(long id, UserLoginVO loginUser) {
        // 校验参数
        ThrowUtils.throwIf(id <= 0 || ObjUtil.isNull(loginUser), ResponseCode.PARAMS_ERROR);
        // 获取图片和用户信息
        Image imageDB = getById(id);
        ThrowUtils.throwIf(imageDB == null, ResponseCode.PARAMS_ERROR);
        // 校验空间以及图片权限
        checkImageAndSpaceAuth(loginUser,imageDB);
        // 开启事务
        transactionTemplate.execute(status -> {
            // 操作数据库
            boolean result = this.removeById(id);
            ThrowUtils.throwIf(!result, ResponseCode.OPERATION_ERROR);
            // 释放额度
            Long spaceId = imageDB.getSpaceId();
            if (spaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, spaceId)
                        .setSql("totalSize = totalSize - " + imageDB.getImgSize())
                        .setSql("totalCount = totalCount - 1")
                        .update();
                ThrowUtils.throwIf(!update, ResponseCode.OPERATION_ERROR, "额度更新失败");
            }
            return true;
        });
    }

    @Override
    public void editImage(ImageEditRequest imageEditRequest, UserLoginVO loginUser) {
        // 校验参数
        ThrowUtils.throwIf(ObjUtil.isNull(loginUser) , ResponseCode.PARAMS_ERROR);
        // 转换成图片实体
        Image image = ImageEditRequest.dtoToObj(imageEditRequest);
        // 校验图片信息
        validImage(image);
        // 校验原图片是否存在
        Image oldImage = getById(imageEditRequest.getId());
        ThrowUtils.throwIf(ObjUtil.isNull(oldImage), ResponseCode.OPERATION_ERROR, "更新图片失败！");
        // 校验空间以及图片权限
        image.setUserId(oldImage.getUserId());
        checkImageAndSpaceAuth(loginUser,image);
        // 校验空间信息是否和原图中的空间一致
        Long spaceId = imageEditRequest.getSpaceId();
        if(ObjUtil.isNull(spaceId)) {
            if(ObjUtil.isNotNull(oldImage.getSpaceId())) {
                image.setSpaceId(spaceId);
            }
        } else {
            ThrowUtils.throwIf(ObjUtil.notEqual(spaceId,oldImage.getSpaceId()), ResponseCode.PARAMS_ERROR, "空间 id 不一致！");
        }
        // 修改图片审核信息
        filterReviewImage(image, loginUser);
        // 编辑图片
        boolean result = updateById(image);
        ThrowUtils.throwIf(!result, ResponseCode.OPERATION_ERROR, "更新图片失败！");
    }

    @Override
    public Page<ImageVO> getImageVOPage(ImageQueryRequest imageQueryRequest,UserLoginVO loginUser) {
        // 校验参数
        ThrowUtils.throwIf(ObjUtil.isNull(loginUser), ResponseCode.PARAMS_ERROR);
        // 获取分页条件
        int current = imageQueryRequest.getCurrent();
        int pageSize = imageQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(pageSize > 100, ResponseCode.PARAMS_ERROR);

        // 空间权限校验
        Long spaceId = imageQueryRequest.getSpaceId();
        // 公开图库
        if (spaceId == null) {
            // 普通用户默认只能查看已过审的公开数据
            imageQueryRequest.setReviewStatus(ReviewStatusEnum.PASS.getValue());
            imageQueryRequest.setNullSpaceId(true);
        } else {
            // 私有空间
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ResponseCode.NOT_FOUND_ERROR, "空间不存在");
//            if (!loginUser.getId().equals(space.getUserId())) {
//                throw new BusinessException(ResponseCode.NO_AUTH_ERROR, "没有空间权限");
//            }
        }
        // 获取到分页数据
        Page<Image> imagePage = this.page(new Page<>(current, pageSize), this.getQueryWrapper(imageQueryRequest));
        List<Image> imageList = imagePage.getRecords();
        // 返回的封装脱敏后数据
        Page<ImageVO> imageVOPage = new Page<>(current, pageSize, imagePage.getTotal());
        if (CollUtil.isEmpty(imageList)) {
            return imageVOPage;
        }
        // 查询出用户id列表，用来批量查询用户信息
        Set<Long> userIdSet = imageList.stream().map(Image::getUserId).collect(Collectors.toSet());
        // 用户 id 映射 用户信息
        Map<Long, List<User>> userIdUserSetMap = userService.getBaseMapper().selectByIds(userIdSet).stream().
                collect(Collectors.groupingBy(User::getId));
        // 封装成脱敏后的数据
        List<ImageVO> imageVOList = new ArrayList<>();
        for (Image image : imageList) {
            Long userId = image.getUserId();
            UserLoginVO userLoginVO = null;
            if (userIdUserSetMap.containsKey(userId)) {
                // 图片的创建用户没有注销的话，还需要返回脱敏后的用户信息
                userLoginVO = UserLoginVO.objToLoginVo(userIdUserSetMap.get(userId).get(0));
            }
            ImageVO imageVO = ImageVO.objToVo(image, userLoginVO);
            imageVOList.add(imageVO);
        }
        // 返回结果
        return imageVOPage.setRecords(orderImageByColor(imageVOList,imageQueryRequest.getImgColor()));
    }

    @Override
    public Page<ImageVO> getImageVOPageHasCache(ImageQueryRequest imageQueryRequest) {
        // 获取分页条件
        int current = imageQueryRequest.getCurrent();
        int pageSize = imageQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(pageSize > 100, ResponseCode.PARAMS_ERROR);

        // 将查询条件构建为缓存的key值
        String sourceKey = JSONUtil.toJsonStr(imageQueryRequest);
        // 本地缓存前缀是通过项目名称:方法名来唯一标识
        String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
        // 获取缓存value值
        String keyPrefix = String.format("%s:%s", ImageConstant.PROJECT_NAME, methodName);
        String cacheValue = cacheManager.getCacheValueByKey(sourceKey, keyPrefix);
        if (StrUtil.isNotBlank(cacheValue)) {
            // 如果命中，直接返回查询结果
            return JSONUtil.toBean(cacheValue, Page.class);
        }

        // 获取到分页数据
        Page<Image> imagePage = this.page(new Page<>(current, pageSize), this.getQueryWrapper(imageQueryRequest));
        List<Image> imageList = imagePage.getRecords();
        // 返回的封装脱敏后数据
        Page<ImageVO> imageVOPage = new Page<>(current, pageSize, imagePage.getTotal());
        if (CollUtil.isEmpty(imageList)) {
            return imageVOPage;
        }
        // 查询出用户id列表，用来批量查询用户信息
        Set<Long> userIdSet = imageList.stream().map(Image::getUserId).collect(Collectors.toSet());
        // 用户 id 映射 用户信息
        Map<Long, List<User>> userIdUserSetMap = userService.getBaseMapper().selectByIds(userIdSet).stream().
                collect(Collectors.groupingBy(User::getId));
        // 封装成脱敏后的数据
        List<ImageVO> imageVOList = new ArrayList<>();
        for (Image image : imageList) {
            Long userId = image.getUserId();
            UserLoginVO userLoginVO = null;
            if (userIdUserSetMap.containsKey(userId)) {
                // 图片的创建用户没有注销的话，还需要返回脱敏后的用户信息
                userLoginVO = UserLoginVO.objToLoginVo(userIdUserSetMap.get(userId).get(0));
            }
            ImageVO imageVO = ImageVO.objToVo(image, userLoginVO);
            imageVOList.add(imageVO);
        }
        Page<ImageVO> result = imageVOPage.setRecords(imageVOList);
        // 存入redis 缓存
        cacheValue = JSONUtil.toJsonStr(result);
        cacheManager.setCacheMap(sourceKey,keyPrefix,cacheValue);
        // 返回结果
        return result;
    }

    @Override
    public CreateImageSynthesisTaskResponse createImageSynthesisTask(CreateImageTaskRequest createImageTaskRequest,
                                                                     UserLoginVO loginUser) {
        // 获取图片信息
        Long imageId = createImageTaskRequest.getImageId();
        Image image = Optional.ofNullable(this.getById(imageId))
                .orElseThrow(() -> new BusinessException(ResponseCode.NOT_FOUND_ERROR));
        // 权限校验
        checkImageAndSpaceAuth(loginUser, image);
        // 构造请求参数
        CreateImageSynthesisTaskRequest taskRequest = new CreateImageSynthesisTaskRequest();
        CreateImageSynthesisTaskRequest.Input input = new CreateImageSynthesisTaskRequest.Input();
        input.setBaseImageUrl(image.getUrl());
        taskRequest.setInput(input);
        BeanUtil.copyProperties(createImageTaskRequest, taskRequest);
        // 创建任务
        return aliYunAiApi.createImageSynthesisTask(taskRequest);
    }

    @Override
    public List<ImageVO> orderImageByColor(List<ImageVO> imageList, String targetHexColor) {
        // 如果没有图片，直接返回空列表
        if (CollUtil.isEmpty(imageList)) {
            return Collections.emptyList();
        }
        // 目标主色调没有传值，不需要排序
        if(StrUtil.isBlank(targetHexColor)) {
            return imageList;
        }
        // 4. 计算相似度并排序
        return imageList.stream()
                .sorted(Comparator.comparingDouble(image -> {
                    // 提取图片主色调
                    String hexColor = image.getImgColor();
                    // 没有主色调的图片放到最后
                    if (StrUtil.isBlank(hexColor)) {
                        return Double.MAX_VALUE;
                    }
                    // 越大越相似
                    return -ColorSimilarUtils.calculateSimilarity(targetHexColor, hexColor);
                }))
                .collect(Collectors.toList());
    }

    @Override
    public QueryWrapper<Image> getQueryWrapper(ImageQueryRequest imageQueryRequest) {
        QueryWrapper<Image> imageQueryWrapper = new QueryWrapper<>();
        if (imageQueryRequest == null) {
            return imageQueryWrapper;
        }
        // 从对象中取值
        String searchText = imageQueryRequest.getSearchText();
        Long id = imageQueryRequest.getId();
        String name = imageQueryRequest.getName();
        String introduction = imageQueryRequest.getIntroduction();
        String category = imageQueryRequest.getCategory();
        List<String> tags = imageQueryRequest.getTags();
        String sortField = imageQueryRequest.getSortField();
        String sortOrder = imageQueryRequest.getSortOrder();
        Integer imgWidth = imageQueryRequest.getImgWidth();
        Integer imgHeight = imageQueryRequest.getImgHeight();
        String imgFormat = imageQueryRequest.getImgFormat();
        Integer reviewStatus = imageQueryRequest.getReviewStatus();
        String reviewMessage = imageQueryRequest.getReviewMessage();
        Long spaceId = imageQueryRequest.getSpaceId();
        boolean nullSpaceId = imageQueryRequest.isNullSpaceId();
        Date startEditTime = imageQueryRequest.getStartEditTime();
        Date endEditTime = imageQueryRequest.getEndEditTime();

        // 拼接查询,查询内容 searchText 在名字中或者简介中都可以匹配
        imageQueryWrapper.and(StrUtil.isNotBlank(searchText), item -> item.like("name", searchText).or().like("introduction", searchText));
        // 标签字符串保存的是 Json 格式的数组，拼接查询需要额外包裹上 "" 才能精准查询
        if (CollUtil.isNotEmpty(tags)) {
            // 通过循环，拼接上所有需要匹配的标签
            for (String tag : tags) {
                imageQueryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 普通查询条件
        imageQueryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        imageQueryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        imageQueryWrapper.eq(StrUtil.isNotBlank(imgFormat), "imgFormat", imgFormat);
        imageQueryWrapper.isNull(nullSpaceId, "spaceId");
        imageQueryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        imageQueryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        imageQueryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        imageQueryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        imageQueryWrapper.like(StrUtil.isNotBlank(category), "category", category);
        imageQueryWrapper.like(ObjUtil.isNotEmpty(imgWidth), "imgWidth", imgWidth);
        imageQueryWrapper.like(ObjUtil.isNotEmpty(imgHeight), "imgHeight", imgHeight);
        imageQueryWrapper.ge(ObjUtil.isNotEmpty(startEditTime), "editTime", startEditTime); // >= startEditTime
        imageQueryWrapper.lt(ObjUtil.isNotEmpty(endEditTime), "editTime", endEditTime); // < endEditTime
        imageQueryWrapper.orderBy(StrUtil.isNotBlank("sortOrder"), sortOrder.equals("ascend"), sortField);
        return imageQueryWrapper;
    }

    @Override
    public void validImage(Image image) {
        ThrowUtils.throwIf(ObjUtil.isNull(image), ResponseCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = image.getId();
        String url = image.getUrl();
        String introduction = image.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ResponseCode.PARAMS_ERROR, "id 不能为空");
        ThrowUtils.throwIf(StrUtil.isNotBlank(url) && url.length() > 1024,
                ResponseCode.PARAMS_ERROR, "url 不能过长");
        ThrowUtils.throwIf(StrUtil.isNotBlank(introduction) && introduction.length() > 512,
                ResponseCode.PARAMS_ERROR, "简介不能过长");
    }

    @Override
    public void reviewImage(ImageReviewRequest imageReviewRequest, UserLoginVO loginUser) {
        // 获取传参数据
        Long id = imageReviewRequest.getId();
        Integer reviewStatus = imageReviewRequest.getReviewStatus();
        ReviewStatusEnum reviewStatusEnum = ReviewStatusEnum.getEnumByValue(reviewStatus);
        // 校验参数
        if (ObjUtil.isNull(id) || ObjUtil.isNull(reviewStatusEnum) || ReviewStatusEnum.REVIEWING.getValue() == reviewStatus) {
            throw new BusinessException(ResponseCode.PARAMS_ERROR);
        }
        // 判断数据库中的图片是否存在
        Image imageDB = this.getById(id);
        ThrowUtils.throwIf(ObjUtil.isNull(imageDB), ResponseCode.PARAMS_ERROR);
        // 数据库中的审核状态和传入参数的审核状态相同
        ThrowUtils.throwIf(imageDB.getReviewStatus().equals(reviewStatus), ResponseCode.PARAMS_ERROR, "请勿重复审核！");
        // 组装更新数据
        Image updateImage = new Image();
        BeanUtil.copyProperties(imageReviewRequest, updateImage);
        updateImage.setReviewerId(loginUser.getId());
        updateImage.setReviewTime(new Date());
        // 更新数据
        boolean result = this.updateById(updateImage);
        ThrowUtils.throwIf(!result, ResponseCode.OPERATION_ERROR, "更新图片审核信息失败！");
    }

    @Override
    public void filterReviewImage(Image image, UserLoginVO loginUser) {
        ThrowUtils.throwIf(ObjUtil.isNull(loginUser), ResponseCode.NOT_LOGIN_ERROR);
        if (UserConstant.USER_ROLE.ADMIN.equals(loginUser.getUserRole())) {
            // 管理员自动过审
            image.setReviewStatus(ReviewStatusEnum.PASS.getValue());
            image.setReviewerId(loginUser.getId());
            image.setReviewMessage("管理员自动过审");
            image.setReviewTime(new Date());
        } else if(ObjUtil.isNotNull(image.getSpaceId())) {
            // 私有空间自动过审
            image.setReviewStatus(ReviewStatusEnum.PASS.getValue());
            image.setReviewerId(loginUser.getId());
            image.setReviewMessage("私有空间自动过审");
            image.setReviewTime(new Date());
        } else {
            // 非管理员，创建或编辑都要改为待审核
            image.setReviewStatus(ReviewStatusEnum.REVIEWING.getValue());
        }
    }

    @Override
    public void checkImageAndSpaceAuth(UserLoginVO loginUser, Image image) {
        // 权限已经通过 sa-Token 里面校验，无需再额外校验
//        Long spaceId = image.getSpaceId();
//        if (spaceId == null) {
//            // 公共图库，仅本人或管理员可操作
//            ThrowUtils.throwIf(!image.getUserId().equals(loginUser.getId()) && !UserConstant.USER_ROLE.ADMIN.equals(loginUser.getUserRole()),
//                    ResponseCode.NO_AUTH_ERROR);
//        } else {
//            // 私有空间，仅本人空间可操作
//            ThrowUtils.throwIf(!image.getUserId().equals(loginUser.getId()), ResponseCode.NO_AUTH_ERROR);
//        }
    }
}